package com.maozzi.service.blog.biz;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maozzi.api.blog.BlogService;
import com.maozzi.api.blog.model.BlogDTO;
import com.maozzi.api.mq.template.MsgTemplate;
import com.maozzi.common.exception.BizException;
import com.maozzi.common.model.PageDTO;
import com.maozzi.common.model.PageParam;
import com.maozzi.common.util.CloneUtil;
import com.maozzi.common.util.ParamCheckUtil;
import com.maozzi.service.blog.constant.BlogConstant;
import com.maozzi.service.blog.domain.BlogDomainService;
import com.maozzi.service.blog.repository.model.Blog;
import javax.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboService;

/**
 * blog service implements
 *
 * @author maozi
 */
@DubboService
public class BlogServiceImpl implements BlogService {
    @Resource
    private BlogDomainService blogDomainService;

    @Resource
    private MsgTemplate msgTemplate;

    @Override
    public PageDTO<BlogDTO> page(BlogDTO dto, PageParam pageParam) throws BizException {
        ParamCheckUtil.notNull(pageParam, "分页参数错误");

        // 查询参数
        Blog blog;
        if (dto == null) {
            blog = null;
        } else {
            blog = CloneUtil.to(dto, Blog.class);
        }

        // 调用service 分页
        Page<Blog> page = blogDomainService.page(blog, pageParam);

        return CloneUtil.toPageDTO(page, BlogDTO.class);
    }

    @Override
    public BlogDTO getById(Long id) throws BizException {
        ParamCheckUtil.notNull(id, "id 为空");

        Blog blog = blogDomainService.getById(id);

        return CloneUtil.to(blog, BlogDTO.class);
    }

    @Override
    public BlogDTO add(BlogDTO dto) throws BizException {
        ParamCheckUtil.notNull(dto, "参数错误");

        Blog blog = CloneUtil.to(dto, Blog.class);
        blogDomainService.save(blog);

        return CloneUtil.to(blog, BlogDTO.class);
    }

    @Override
    public void editById(BlogDTO dto) throws BizException {
        ParamCheckUtil.notNull(dto, "参数错误");
        ParamCheckUtil.notNull(dto.getId(), "id 为空");

        Blog blog = CloneUtil.to(dto, Blog.class);

        blogDomainService.editById(blog);
    }

    @Override
    public void delById(Long id) throws BizException {
        // blogDomainService.del(id);
        // 模拟send msg

        BlogDTO dto = new BlogDTO();
        dto.setId(id);
        dto.setKey("blog");
        dto.setSource("blog-del");

        msgTemplate.send(BlogConstant.BLOG_TOPIC, BlogConstant.BLOG_DEL_TAG, dto);
    }
}
